import React, { useRef, useState } from 'react'
import { PageContainer } from '@ant-design/pro-layout'
import ProTable from '@ant-design/pro-table'
import ProTableConfig from '@/pages/Report/ProTableConfig'
import { operationReport } from '@/services/report'
import GetTime from '@/components/GetTime'

export default function Operation () {
  /** 设置 loading **/
  const [loading, setLoading] = useState(false)
  const actionRef = useRef()
  /** 表单请求 **/
  const tableRequest = async (params) => {
    setLoading(true)
    // 更改默认属性名 current
    params = JSON.parse(JSON.stringify(params).replace(/current/g, 'page'))

    const data = await operationReport(params)

    setLoading(false)
    return {
      data: data.data,
      success: true,
      total: data.meta.pagination.total
    }
  }

  /** 设置 table 字段 **/
  const columns = [
    {
      title: '编号',
      key: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: '5%'
    },
    {
      title: '操作用户',
      key: 'username',
      dataIndex: 'user_id',
      width: '15%',
      render: (text, record) => {
        return record.user.username
      },
    },
    {
      title: '时间区间',
      key: 'dateTimeRange',
      dataIndex: 'createdAtRange',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1]
          }
        },
      },
    },
    {
      title: '操作地址',
      key: 'path',
      dataIndex: 'path',
      width: '15%',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作ip',
      key: 'ip',
      dataIndex: 'ip',
      ellipsis: true,
      width: '15%',
      hideInSearch: true,
    },
    {
      title: '操作描述',
      key: 'describe',
      dataIndex: 'describe',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '操作时间',
      key: 'createdAt',
      dataIndex: 'created_at',
      valueType: 'fromNow',
      hideInSearch: true
    },
    {
      title: '操作时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTime',
    },
  ]

  return (
    <PageContainer header={{
      extra: [
        <GetTime key="getTime"/>
      ]
    }}>
      <ProTable
        {...ProTableConfig}
        dateFormatter="string"
        tableLayout="fixed"
        actionRef={actionRef}
        loading={loading}
        columns={columns}
        params={{ include: 'user' }}
        request={(params, sort) => tableRequest(params, sort)}
      >
      </ProTable>
    </PageContainer>
  )
}
